//#define TESTING
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Threading;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.Office.Project.EPMAuditing.ReceiverService.Monitor.Properties;
using Microsoft.Office.Project.EPMAuditing.Library;
using System.Reflection;

namespace Microsoft.Office.Project.EPMAuditing.ReceiverService.Monitor
{
    public partial class FormMain : Form
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        private ManualResetEvent _pause = new ManualResetEvent(false);
        private Thread _workerThread;
        private FormDisplay _fd;
        private ServiceController _serviceController;
        private bool _editListenerDialogOpen = false;


#if TESTING
        private const string _epmAuditServiceName = "Spooler";
#else
        private const string _epmAuditServiceName = "EPMAuditing Receiver Service";
#endif
        public FormMain()
        {
            InitializeComponent();
            ConnectToEPMAuditng();
        }

        private void ConnectToEPMAuditng()
        {
            try
            {
                if (_serviceController == null)
                    _serviceController = new ServiceController(_epmAuditServiceName);

                toolStripMenuItemRunEPMAuditng.Enabled = true;
                _serviceController.Refresh();
                if (_serviceController.Status != ServiceControllerStatus.Running)
                    toolStripMenuItemRunEPMAuditng.Text = String.Format(CultureInfo.InvariantCulture, "{0} {1}", Resources.Start, _epmAuditServiceName);
                else
                    toolStripMenuItemRunEPMAuditng.Text = String.Format(CultureInfo.InvariantCulture, "{0} {1}", Resources.Stop, _epmAuditServiceName);
            }
            catch (InvalidOperationException)
            {
                // EPMAuditService not found
                _serviceController = null;
                toolStripMenuItemRunEPMAuditng.Enabled = false;
            }

            catch (ArgumentException)
            {
                _serviceController = null;
                toolStripMenuItemRunEPMAuditng.Enabled = false;
            }
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            // Spawn thread to get updates on the toolbar icon
            NotifyIconUpdate niu = new NotifyIconUpdate(this.notifyIcon1, _epmAuditServiceName, _pause);

            _workerThread = new Thread(new ThreadStart(niu.UpdateMethod));
            _workerThread.Start();
            _pause.Set();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            _pause.Reset();
            _workerThread.Abort();
        }

        private void toolStripMenuItemExit_Click(object sender, EventArgs e)
        {
            if (_fd != null)
                _fd.Close();

            this.Close();
        }

        private void toolStripMenuItemShow_Click(object sender, EventArgs e)
        {
            ShowDisplay();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ShowDisplay();
        }

        private void ShowDisplay()
        {
            if (_fd == null)
            {
                _fd = new FormDisplay();
                _fd.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.fd_FormClosed);
            }
            _fd.Show();
            SetForegroundWindow(_fd.Handle);
        }

        private void fd_FormClosed(Object sender, FormClosedEventArgs e)
        {
            _fd = null;
        }

        //private void toolStripMenuItemShowTrace_Click(object sender, EventArgs e)
        //{
        //    ShowTrace();
        //}

        //private void ShowTrace()
        //{
        //    if (_tw == null)
        //    {
        //        _tw = new FormTraceWindow();
        //        _tw.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.tw_FormClosed);
        //    }
        //    _tw.Show();
        //    SetForegroundWindow(_tw.Handle);
        //}

        //private void tw_FormClosed(Object sender, FormClosedEventArgs e)
        //{
        //    _tw = null;
        //}

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            ConnectToEPMAuditng();
        }

        private void toolStripMenuItemEditListeners_Click(object sender, EventArgs e)
        {
            ShowEditListeners();
        }

        private void ShowEditListeners()
        {
            if (!_editListenerDialogOpen)
            {
                FormEditListeners el = new FormEditListeners(_epmAuditServiceName);
                _editListenerDialogOpen = true;
                if (el.ShowDialog() == DialogResult.OK)
                {
                    if (el.Dirty)
                        ExecuteRefreshListenerList();
                }
                _editListenerDialogOpen = false;
                el.Close();
            }
        }

        private void toolStripMenuItemRunEPMAuditing_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serviceController.Status != ServiceControllerStatus.Running)
                    _serviceController.Start();
                else
                    _serviceController.Stop();
            }
            catch (Win32Exception ex)
            {
                MessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.Win32Exception, ex.Message),
                    Resources.MonitorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ConnectToEPMAuditng();
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show(String.Format(CultureInfo.InvariantCulture, Resources.ServiceException, ex.Message),
                    Resources.MonitorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ConnectToEPMAuditng();
            }
        }

        //private void toolStripMenuItemRefreshListeners_Click(object sender, EventArgs e)
        //{
        //    ExecuteRefreshListenerList();
        //}

        private void ExecuteRefreshListenerList()
        {
            try
            {
                ServiceController myService = new ServiceController(_epmAuditServiceName);
                myService.ExecuteCommand((int)SimpleServiceCustomCommand.ExecuteRefreshListenerList);
                MessageBox.Show("New Listener List sent to service", "EPM Auditing", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("Refresh Listener List failed", "EPM Auditing", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripMenuItemOpenAudit_Click(object sender, EventArgs e)
        {
            string fullPath = Assembly.GetExecutingAssembly().Location;
            string directory = fullPath.Substring(0, fullPath.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1);
            OpenExplorer(String.Format(CultureInfo.InvariantCulture, @"{0}Audit Logs\", directory));
        }

        private void toolStripMenuItemOpenDebug_Click(object sender, EventArgs e)
        {
            string fullPath = Assembly.GetExecutingAssembly().Location;
            string directory = fullPath.Substring(0, fullPath.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1);
            OpenExplorer(String.Format(CultureInfo.InvariantCulture, @"{0}Trace\", directory));
        }

        private void OpenExplorer(string path)
        {
            System.Diagnostics.Process.Start("explorer.exe", path);
        }


    }
}